#pragma once

#include <iostream>
#include <stdarg.h>
#include <time.h>
#include <unistd.h>
#include <string>
#include <cstring>
#include <cerrno>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

using namespace std;

#define Info 0
#define Debug 1
#define Warning 2
#define Error 3
#define Fatal 4

#define SIZE 1024

#define Screen 0
#define Onefile 1
#define Classfile 2

#define Logname "./log/log.txt"

class Log;

extern Log lg;

class Log
{
public:
    Log()
    {}

    void Enable(int method)
    {
        _printMethod = method;
    }

    string levelToString(int level)
    {
        switch (level)
        {
        case Info:
            return "Info";
        case Debug:
            return "Debug";
        case Warning:
            return "Warning";
        case Error:
            return "Error";
        case Fatal:
            return "Fatal";
        dafault:
            return "None";
        }
    }

    void operator()(int level, const char *format, ...)
    {
        char leftbuf[SIZE];
        time_t t = time(nullptr);
        struct tm *ctime = localtime(&t);

        snprintf(leftbuf, sizeof(leftbuf), "[%s][%d-%d-%d  %d:%d:%d]:", levelToString(level).c_str(),
                 ctime->tm_year + 1900, ctime->tm_mon + 1, ctime->tm_mday,
                 ctime->tm_hour, ctime->tm_min, ctime->tm_sec);

        char rightbuf[SIZE];
        va_list s;
        va_start(s, format);

        vsnprintf(rightbuf, sizeof(rightbuf), format, s);

        va_end(s);

        char logtxt[2 * SIZE];
        snprintf(logtxt, sizeof(logtxt), "%s %s", leftbuf, rightbuf);

        Print(level,logtxt);
    }

    void Print(int level,const string& logtxt)
    {
        switch(_printMethod)
        {
            case Screen:
                cout << logtxt << endl;
            break;
            case Onefile:
                printOnefile(Logname,logtxt);
            break;
            case Classfile:
                printClassfile(level,logtxt);
            break;
            default:
            break;
        }
    }

    void printOnefile(const string& logname, const string& logtxt)
    {
        int fd = open(logname.c_str(),O_WRONLY|O_CREAT|O_APPEND,0664);
        if(fd < 0) return;
        
        write(fd,logtxt.c_str(),logtxt.size());

        close(fd);
    }

    void printClassfile(int level,const string& logtxt)
    {
        string filename(Logname);
        filename += '.';
        filename += levelToString(level);
        printOnefile(filename,logtxt);
    }

    ~Log()
    {}
private:
    int _printMethod = Screen;
};



// int sum(int n, ...)
// {
//     va_list s;
//     va_start(s, n); // 让s找到可变参数的起始地址

//     int sum = 0;
//     while (n--)
//     {
//         sum += va_arg(s, int);
//     }

//     va_end(s);

//     return sum;
// }